package com.agileai.portal.notice;

import java.net.URL;
import java.util.HashMap;
import java.util.List;

import org.apache.cxf.endpoint.Client;
import org.apache.cxf.frontend.ClientProxy;
import org.apache.cxf.transport.http.HTTPConduit;
import org.apache.cxf.transports.http.configuration.HTTPClientPolicy;

import com.agileai.common.AppConfig;
import com.agileai.hotweb.common.BeanFactory;
import com.agileai.portal.notice.intercepter.ClientSoapHeader;
import com.agileai.portal.notice.wsclient.NoticeSend;
import com.agileai.portal.notice.wsclient.NoticeSendProxy;

public class PortalMessageSender {
	private static HashMap<String,NoticeSendProxy> ProxyCache = new HashMap<String,NoticeSendProxy>();
	private AppConfig appConfig = null;
	
	public PortalMessageSender(){
		appConfig = BeanFactory.instance().getAppConfig();
	}
	
	 private NoticeSendProxy getNoticeSendProxy(String wsdlLocation){
    	if(!ProxyCache.containsKey(wsdlLocation)){
    		try {
    			URL url = new URL(wsdlLocation);
    			NoticeSend noticeSend = new NoticeSend(url);
    			NoticeSendProxy temp = noticeSend.getNoticeSendProxyPort();
    			ProxyCache.put(wsdlLocation, temp);
			} catch (Exception e) {
				e.printStackTrace();
			}
    	}
    	return ProxyCache.get(wsdlLocation);
    }
	    
	public void sendMessage(List<java.lang.String> userCodes,String msgTitle,String msgContent,String senderCode){
		try {
			String wsdlLocation = appConfig.getConfig("GlobalConfig", "ServiceURL");
			NoticeSendProxy noticeSendProxy = getNoticeSendProxy(wsdlLocation);
			Client clientProxy = ClientProxy.getClient(noticeSendProxy);
			String authUserId = appConfig.getConfig("GlobalConfig", "ServiceAuthUserId");
			String authPassword = appConfig.getConfig("GlobalConfig", "ServiceAuthPassword");
			
			ClientSoapHeader ash = new ClientSoapHeader(authUserId,authPassword);
			clientProxy.getOutInterceptors().add(ash);
			
			HTTPConduit http = (HTTPConduit) clientProxy.getConduit();
			HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
			httpClientPolicy.setConnectionTimeout(Integer.valueOf(60000));
			httpClientPolicy.setReceiveTimeout(Integer.valueOf(60000));
			httpClientPolicy.setAllowChunking(false);
			http.setClient(httpClientPolicy);
			
			noticeSendProxy.sendMessage(userCodes, msgTitle, msgContent, senderCode);		
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
